﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TireBias.Models;
using WinNemoLib;
using System.Data;

namespace TireBias.Controllers
{
   public class BiasHeadController : Controller
   {
      //
      // GET: /BiasHead/
       public ActionResult test()
       {
           return View();
       }

      public void Regis_User(string emp, string code)
      {

         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, emp
             , DateTime.Now, DateTime.Now.AddMinutes(60), true, code);

         // Encrypt the cookie using the machine key for secure transport
         string hash = FormsAuthentication.Encrypt(ticket);
         HttpCookie cookie = new HttpCookie(
            FormsAuthentication.FormsCookieName, // Name of auth cookie
            hash); // Hashed ticket

         // Set the cookie's expiration time to the tickets expiration time
         if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

         Response.Cookies.Add
         (
             new HttpCookie
             (
                 FormsAuthentication.FormsCookieName,
                 FormsAuthentication.Encrypt(ticket)
             )
         );

      }

      public JsonResult Register(string emp, string code, string biasno)
      {
         
         KANBANPlanModel mdSearch = new KANBANPlanModel();
         KANBANPlanModel.KANBANPlan_DS item = mdSearch.GET_BIASNO(code);
         Regis_User(emp, code);
         if (item._itemno == "H")
         {
            ViewBag.url = "Index";
            return Json(new { success = 1, message = "บันทึกเรียบร้อย", biasno = item._biasno, gotoURL = Url.Action("CheckProcess") + "?biasno=" + item._biasno  });
         }
         if (item._itemno == "T")
         {
             return Json(new { success = 1, message = "บันทึกเรียบร้อย", biasno = item._biasno, gotoURL = Url.Action("CheckProcess", "BiasTail") + "?biasno=" + item._biasno});
         }

         return Json(new { success = 0, message = "ไม่พบข้อมูล" });
      }


      public ActionResult CheckProcess(string biasno)
      {
          SessionBag.Current.biasno = biasno;
          
          ViewBag.biasno = biasno;
          
         List<BIASSUBPlanModel.BIASSUBPlan_DS> sub = new List<BIASSUBPlanModel.BIASSUBPlan_DS>();
         BIASSUBPlanModel mSub = new BIASSUBPlanModel();
         sub= mSub.SEL_HEAD_NOFIN(biasno,"","");

         if (sub.Count > 0)
         {    
             BIASSUBPlanModel.BIASSUBPlan_DS model = sub[0];
             // Case Sample
             if (StrUtil.IsNotEmpty(model._sauthemp))
             {
                 if (StrUtil.IsNotEmpty(model._Rundt))
                 {
                     return RedirectToAction("New_Sample_PROC", "NewSample", new { seq = model._plandt + "-" + model._itemno });

                 }
                 else if (StrUtil.IsNotEmpty(model._Ply1))
                 {
                    return RedirectToAction("New_Sample_SUB", "NewSample", new { seq = model._plandt + "-" + model._itemno });
                 }
                 return RedirectToAction("New_Sample", "NewSample", new { seq = model._plandt + "-" + model._itemno });
             }
      
            if (StrUtil.IsEmpty(model._Rundt))
            {
               return RedirectToAction("Use_KANBAN", "BiasHead_KANBAN", new { seq = model._plandt + "-" + model._itemno, biasno = model._biasno, shift = model._shift });
            }
            else if(StrUtil.IsEmpty(model._finflag)){
              //string seq, string biasno, string shift, string subItem

                return RedirectToAction("GET_PDF_INF", "BiasHead_KANBAN", new { seq = model._plandt + "-" + model._itemno, biasno = model._biasno, shift = model._shift,subItem = model._sitemno });

                }
            else
            {
               return RedirectToAction("Use_KANBAN",  new { seq = model._plandt + "-" + model._itemno, biasno = model._biasno, shift = model._shift });

            }
         }


         List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
         BIASPLANModel mdSearch = new BIASPLANModel();
         list = mdSearch.GET_NOT_FINISH("", biasno);
         if (list.Count > 0)
         {
            BIASPLANModel.BIASPLAN_DS model = list[0];
            // Case Sample
            if (StrUtil.IsNotEmpty(model._Smpemp))
            {
                return RedirectToAction("New_Sample", "NewSample", new { seq = model._Plandt + "-" + model._Itemno });
            }
            else if (StrUtil.IsNotEmpty(model._tcrdlot))
            {
               return RedirectToAction("Use_KANBAN", new { seq = model._Plandt + "-" + model._Itemno, biasno = model._Biasno, shift = model._Shift });
            }
            //else if (model._Actflag == "X")
            //{
            //   return RedirectToAction("Header_line_barcode", new { seq = model._Plandt + "-" + model._Itemno, biasno = model._Biasno, shift = model._Shift });

            //}
         }

         return RedirectToAction("Header_line", new { biasno = biasno });
      }

      public ActionResult NO_PROCESS(string msg)
      {
          if (StrUtil.IsEmpty(msg)) msg = "NO PROCESS";
          ViewData["Message"] = msg;
          return View();
      }
      public ActionResult Index()
      {
         FormsAuthentication.SignOut();

         return View();
      }

      public ActionResult Header_line(string biasno)
      {
         ViewBag.Full = "F";
         if (StrUtil.IsNotEmpty(biasno))
         {
             SessionBag.Current.biasno = biasno;
           
         }

         List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
         BIASPLANModel mdSearch = new BIASPLANModel();
         list = mdSearch.GET_TOPCORDPLN_ACT("", "", biasno, "L","",true);
         if (list.Count() <= 0)
         {
             return RedirectToAction("NO_PROCESS");
         }
         return View(list);
      }


      public ActionResult Header_line_barcode(string seq, string biasno)
      {
         ViewBag.Full = "F";
         //SessionBag.Current.biasno = biasno;
         //SessionBag.Current.shift = shift;

         List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
         BIASPLANModel mdSearch = new BIASPLANModel();

         if (mdSearch.UPDATE(User.Identity.Name.ToString(), "A", seq, "", biasno) == false)
         {
             return RedirectToAction("NO_PROCESS", new { msg = "Modify Plan (Check Update)" });
         }
         else
         {
             list = mdSearch.GET_TOPCORDPLN_ACT("", "1", biasno, "L");
             return View(list[0]);
         }
      }

      public ActionResult Old_ToppedCode(string seq, string biasno, string oldSeq)
      {
          ViewBag.Full = "F";
          List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
          BIASPLANModel mdSearch = new BIASPLANModel();
          mdSearch.UPDATE(User.Identity.Name.ToString(), "A", seq, "", SessionBag.Current.biasno);
          TailModel md = new TailModel();
          DataTable dt = md.GET_SHIFT();
          TireBias.Models.SessionBag.Current.shift = dt.Rows[0]["shift"].ToString();
          list = mdSearch.GET_TOPCORDPLN_ACT("", "1", SessionBag.Current.biasno, "L");
          list[0]._OldSeq = oldSeq;
          return View(list[0]);
      }

      public JsonResult Save_Date(List<KANBANPlanModel.KANBANPlan_DS> theData)
      {

         KANBANPlanModel.KANBANPlan_DS data = theData[0];

         KANBANPlanModel mdUpd = new KANBANPlanModel();
         data._empname = User.Identity.Name;

         if (mdUpd.UPD_KANBANPLAN(data))
         {
            return Json(new { success = 1, message = "บันทึกเรียบร้อย" });
         }
         else
         {
            return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
         }

      }

      public JsonResult Get_Author(string users, string pass)
      {

          System.Data.DataTable dt = LoginAuthorize.DataAcess.MasterGroupNameDA.SEL_UserInfo(users, LoginAuthorize.EnCodeMD5.MD5CalcString(pass), "11-014");
         if (dt == null)
         {
            return Json(new { success = 0, message = "The user name or password provided is incorrect." });
         }
         return Json(new { success = 1, message = "" });
      }

      public JsonResult ConvertDate(string sdate)
      {

         string a = DateUtil.ToDisplayDate(sdate, WinNemoLib.DateUtil.eLanguage.EN);
         Conn vai = new Conn();
         sdate = DateUtil.ToInternalDate(sdate, DateUtil.eLanguage.EN);
         return Json(new { bln = vai.GetDateTimeDiffCurrent(sdate), message = a });

      }

      public ActionResult RollBack(string seq, string st = "1", string biasno = "")
      {

         BIASPLANModel mdSearch = new BIASPLANModel();
         mdSearch.ROLLBACK_STATUS(User.Identity.Name, st, seq, biasno);

            return RedirectToAction("Header_line", new { biasno = biasno });

   
      }

      // USE KANBAN
      public ActionResult Use_KANBAN(string seq, string biasno)
      {
         ViewBag.Full = "F";         
         ViewBag.biasno = SessionBag.Current.biasno;
   
         string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
         List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
         BIASPLANModel mdSearch = new BIASPLANModel();

         list = mdSearch.GET_TOPCORDPLN_ACT(seqs[0],"1", SessionBag.Current.biasno, "", seqs[1]);
         if (list.Count > 0)
         {
             if (Convert.ToInt16(list[0].cP1) > 0) return View(list[0]);
             if (Convert.ToInt16(list[0].cP2) > 0) return View(list[0]);
             if (Convert.ToInt16(list[0].cP3) > 0) return View(list[0]);
             if (Convert.ToInt16(list[0].cP4) > 0) return View(list[0]);
       
         }
         return RedirectToAction("Header_line", new { biasno = biasno });
      }


      public JsonResult SAVE_SUB_ITEM(List<BIASSUBPlanModel.BIASSUBPlan_DS> theData)
      {

         BIASSUBPlanModel.BIASSUBPlan_DS data = theData[0];

         BIASSUBPlanModel mdUpd = new BIASSUBPlanModel();
         data._empname = User.Identity.Name;
         data._sitemno = mdUpd.GET_SEQ(data._plandt, data._biasno, data._itemno);
         using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
         {
            cnn.Open();
            cnn.BeginTransaction();
            if (mdUpd.Ins_Data(cnn, data, User.Identity.Name))
            {
               cnn.CommitTransaction();
               return Json(new { success = 1, message = "บันทึกเรียบร้อย" });
            }
            else
            {
               cnn.RollbackTransaction();
               return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
            }
         }
      }

      //SKIP DATA

      public JsonResult SKIP_ITEM(string seq, string empnm, string sTxt)
      {

          BIASSUBPlanModel mdChk = new BIASSUBPlanModel();
          string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
          List<TireBias.Models.KANBANPlanModel.KANBANPlan_DS> data = new List<TireBias.Models.KANBANPlanModel.KANBANPlan_DS>();
            data =   mdChk.GET_KANBANPLAN_SUB(SessionBag.Current.biasno, seqs[0], seqs[1]);

            if (data.Count > 0) { 
              return Json(new { success = 0, message = "ไม่สามารถบันทึกได้ เนื่องจากมีการใช้งานแล้ว" });
            }

          KANBANPlanModel mdSearch = new KANBANPlanModel();

          if (mdSearch.SKIP_STATUS(seq, empnm, sTxt,SessionBag.Current.biasno) == true)
          {
              return Json(new { success = 1, message = "" });
          }
          else
          {
              return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
          }
      }


       //Summery Roll use
      public JsonResult GET_USE(string seq, string biasno)
      {
    
          List<TailModel.TailBias_DS> list = new List<TailModel.TailBias_DS>();
          if (StrUtil.IsEmpty(seq))
          {
              return Json(list);
          }
          ViewBag.Full = "F";
          string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
          
          TailModel mdSearch = new TailModel();
          list = mdSearch.SUM_PLYROLL(biasno, seqs[0], seqs[1]);
          if (list.Count() <= 0) return Json("");
          return Json(list);
      }

      public JsonResult Get_LastFinish(string code)
      {
          List<KANBANPlanModel.KANBANPlan_DS> list = new List<KANBANPlanModel.KANBANPlan_DS>();
          KANBANPlanModel mSearch = new KANBANPlanModel();
          list = mSearch.GET_LAST_FINISH(SessionBag.Current.biasno);
          if (list.Count <= 0)
          {
              return Json(new { seq = "" });
          }
          if (list[0]._topcrdcd == code)
          {
              return Json(new { seq = list[0]._plandt+'-'+list[0]._itemno });
          }
           return Json(new { seq = "" });
      }
      public JsonResult Get_Detail(string seq)
      {
          List<KANBANPlanModel.KANBANPlan_DS> list = new List<KANBANPlanModel.KANBANPlan_DS>();
          KANBANPlanModel mSearch = new KANBANPlanModel();
          string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
          list = mSearch.SEL_KANBANPLAN(SessionBag.Current.biasno, seqs[0], seqs[1],false);       
          return Json(list);
      }



   }
  
}
